<template>
	<view class="ad" v-if="isShowAd">
		<view class="ad-popup">
			<view class="ad-title">
				发现待添加设备：{{list.length}}个
			</view>
			<view v-if="list.length == 1" class="ad-img ad-device">
				<image class="icon-img" :key="index" data-code="601113" data-eventName="click_scan_blue_dev_pop_item" @click="toFindDeviceList" :src="list[0].deviceInfo.devicePic"/>
				<view>{{list[0].deviceInfo.deviceTypeName}}</view>
			</view>
			<view v-if="list.length > 1" class="ad-img-m ad-device">
				<view class="">
					<image class="device-img" v-for="(item,index) in list" :key="index"  :src="item.deviceInfo.devicePic">
					</image>
				</view>
				<view class="ad-img-icon">
					<uni-icons type="plus-filled" @click="toFindDeviceList" color="#FF0025" size="30"></uni-icons>
				</view>
			</view>
			<view v-if="list.length == 1" class="ad-button">
				<button class="add-button" type="default" @click="cancel()" plain="true">取消</button>
				<button class="confirm-button add-button" type="default" @click="toFindDeviceList" plain="true">确定</button>
			</view>
			<view v-if="list.length > 1" class="ad-button">
				<button class="add-button" style="width: 90%;" type="default" @click="cancel()" plain="true">取消</button>
			</view>
		</view>
	</view>
</template>

<script>
	const {
		ab2hex,
		hexToString
	} = require('@/utils/util.js');

	export default {
		data() {
			return {
				isShowAd: false,// 是否显示弹窗
				list: [],// 设备列表
				isStop: false,
			};
		},
		created() {
			if (uni.getStorageSync('adddevice') != 1) {
				if (uni.getStorageSync('accessToken')) {
					this.openBluetoothAdapter();
				}
			}
		},
		mounted() {
			// 更新设备信息
			uni.$on('stopBlue', (data) => {
				if (this.isStop) {
					// 停止搜索蓝牙设备
					this.stopBluetoothDevicesDiscovery();
					// 断开蓝牙模块
					this.closeBluetoothAdapter()
				}
			})
		},
		destroyed() {
			console.log('destroyed首页弹窗')
			this.stopBluetoothDevicesDiscovery();	// 停止搜索蓝牙设备
			this.closeBluetoothAdapter() // 断开蓝牙模块
		},
		methods: {
			// 初始化蓝牙
			openBluetoothAdapter() {
				uni.openBluetoothAdapter({
					success: e => {
						console.log('首页初始化蓝牙成功:' + e);
						this.isStop = true;
						this.getBluetoothAdapterState();
						this.startBluetoothDevicesDiscovery()
					},
					fail: e => {
						console.log('首页初始化蓝牙失败，错误码：' + (e.errCode || e.errMsg));
						this.$logs({
							info: '蓝牙初始化失败',
							res: e
						})
					}
				});
			},
			// 开始搜索蓝牙设备
			startBluetoothDevicesDiscovery() {
				uni.startBluetoothDevicesDiscovery({
					// services: ['A201'],
					success: e => {
						this.onBluetoothDeviceFound();
					},
					fail: e => {
						uni.showToast({
							title: e.errCode
						})
					}
				});
			},
			// 停止搜索蓝牙设备
			stopBluetoothDevicesDiscovery(types) {
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						console.log('停止搜索蓝牙设备:' + e.errMsg);
					},
					fail: e => {}
				});
			},
			// 获取本机蓝牙适配器状态
			getBluetoothAdapterState() {
				uni.getBluetoothAdapterState({
					success: res => {
						this.adapterState = res;
					},
					fail: e => {}
				});
			},
			// 发现外围设备
			onBluetoothDeviceFound() {
				uni.onBluetoothDeviceFound(devices => {
					this.getBluetoothDevices();
				});
			},
			// 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
			getBluetoothDevices() {
				uni.getBluetoothDevices({
					success: res => {
						let tempList = []
						this.list = []
						res.devices.forEach((item, index) => {
							let advertisDataStr = ab2hex(item.advertisData)
							if (advertisDataStr.endsWith('8b8b8b8b') || advertisDataStr.startsWith('8b8b')) {
								for (let key in item.serviceData) {
									this.$set(item, 'pid', hexToString(ab2hex(item.serviceData[key])))
									this.$set(item, 'advertisDataStr', advertisDataStr)
									//根据Pid获取设备信息
									getApp().globalData.api.getDeviceInfoByPID({
										pid: hexToString(ab2hex(item.serviceData[key]))
									}, (result) => {
										if(result.data.code == 2000){
											this.$set(item, 'deviceInfo', result.data.data)
										}else{
											let info = {
												devicePic:'https://statics.xmcsrv.net/weixin/lockIcon.png',
												deviceTypeName:'屏显智能云锁'
											}
											this.$set(item, 'deviceInfo', info)
										}
									},false,false);
								}
								tempList.push(item)
							}
						})
						let isPush = false
						if (tempList.length !== 0) {
							tempList.forEach((item) => {
								if (item.serviceData) {
									isPush = true
								}
							})
							if (isPush) {
								this.list = tempList
							}
						}
						if (this.list.length !== 0) {
							this.isShowAd = true;
							const pages = getCurrentPages()
							const page = pages.pop()
							if (page.route.includes('/device/home')) {
								uni.hideTabBar();
							}
							uni.setStorageSync("adddevice", 1);
							this.list.forEach((item) => {
								let info = {
									devicePic: 'https://statics.xmcsrv.net/weixin/lockIcon.png',
									deviceTypeName: '屏显智能云锁'
								}
								if (!item.pid) {
									this.$set(item, 'deviceInfo', info)
								}
							})
							setTimeout(() => {
								this.stopBluetoothDevicesDiscovery()
							}, 100)
						}
					},
					fail: e => {
						if (e.errCode !== 0) {}
						this.$logs({
							info: '获取蓝牙设备错误',
							res: e
						})
					}
				});
			},
			cancel() {
				this.isShowAd = false;
				uni.showTabBar();
				setTimeout(() => {
					uni.$emit('refreshSize') //刷新新UI高度
				}, 100)
				this.stopBluetoothDevicesDiscovery();
				this.closeBluetoothAdapter();
			},
			//跳转找到设备页
			toFindDeviceList() {
				let list = []
				this.list.forEach((item) => {
					list.push(item.deviceInfo)
				})
				uni.navigateTo({
					url: '/jvss/pagesDevice/device/bluetooth/findEquipment?deviceList=' + JSON.stringify(this.list)
				})
				this.isShowAd = false;
				uni.showTabBar();
			},
			// 断开蓝牙模块
			closeBluetoothAdapter(OBJECT) {
				uni.closeBluetoothAdapter({
					success: res => {
						console.log('断开蓝牙模块成功');
					}
				});
			},
		}
	};
</script>
<style lang="scss">
	.ad {
		position: fixed;
		width: 100%;
		height: 100vh;
		z-index: 999;
		top: 0;
		background-color: rgba(0, 0, 0, 0.4);
	}

	.ad-popup {
		width: 90%;
		min-height: 30vh;
		background-color: #fff;
		margin: 5%;
		position: absolute;
		bottom: 20rpx;
		border-radius: 20rpx;
		z-index: 999;
		animation: animate .2s ease;
		animation-iteration-count: 1;

		.ad-device {
			margin: 40rpx 30rpx;
			margin-bottom: 100rpx;
		}

		.ad-img {
			text-align: center;

			.icon-img {
				width: 140rpx;
				height: 140rpx;
				margin: 10rpx 0;
			}
		}

		.ad-img-m {
			display: flex;
			justify-content: space-between;
			align-items: center;
			min-height: 260rpx;
			overflow-y: auto;

			.device-img {
				width: 100rpx;
				height: 100rpx;
				margin: 10rpx;
			}
		}
	}

	@keyframes animate {
		from {
			bottom: -520rpx;
		}

		to {
			bottom: 20rpx;
		}
	}

	.ad-title {
		text-align: center;
		padding: 20rpx;
		font-weight: 600;
	}

	.ad-button {
		height: 80rpx;
		width: 90%;
		display: flex;
		justify-content: space-around;
		align-items: center;
		position: absolute;
		bottom: 10rpx;
		margin: 0 5%;
		
        .add-button{
			width: 38%;
			height: 60rpx;
			line-height: 60rpx;
			font-size: 24rpx;
			border: 1px solid #B9B9B9 !important;
		}
		
		.confirm-button {
			color: #FF0025 !important;
		}
		
		
	}
</style>
